package com.example.bindservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    MediaPlayer mediaPlayer;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("msg ", "onBind()");
        return  new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.qifengle);
    }

    @Override
    public void onDestroy() {//销毁 player
        super.onDestroy();
        Log.i("msg ", "onDestroy()");
        if (mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.release();//释放 MediaPlayer 对象
        }
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("msg ", "onUnbind()");
        return super.onUnbind(intent);
    }

    public void play(){
        if (mediaPlayer==null){
            mediaPlayer=MediaPlayer.create(this,R.raw.qifengle);
            mediaPlayer.start();
            return;
        }
        if (mediaPlayer!=null && !mediaPlayer.isPlaying()){//暂停状态
            mediaPlayer.start();
            return;
        }
        if (mediaPlayer!=null && mediaPlayer.isPlaying()){//播放状态,重新播放
            mediaPlayer.seekTo(0);
            mediaPlayer.start();
            return;
        }
    }
    public void pause(){
        if (mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
    }
    public void stop(){
        if (mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.prepareAsync();
        }
    }



    class MyBinder extends Binder{
        public  MyService getService(){
            return  new MyService();
        }
    }




}
